<?php
namespace Api\Controller;

use Think\Controller;
use Think\Exception;

class CookbookController extends Controller
{

    protected $cookbook_model;
    protected $banner_model;
    protected $classify_model;
    protected $collect_model;
    protected $praise_model;
    protected $cooking_model;
    protected $review_model;
    protected $review_image_model;

    function __construct()
    {
        parent::__construct();
        $this->cookbook_model = D("Common/Cookbook");
        $this->banner_model = D("Common/Banner");
        $this->classify_model = D("Common/Classify");
        $this->collect_model = D("Common/Collect");
        $this->praise_model = D("Common/Praise");
        $this->cooking_model = D("Common/Cooking");
        $this->review_model = D("Common/Review");
        $this->review_image_model = D("Common/ReviewImage");

    }

    // 根据一级分类id分页获取所有菜谱列表
    public function getCookbookList()
    {
        $pid = I('pid');
        $page = I('page');
        $pages = ($page - 1) * 8;
        $sql = "SELECT cc.* FROM cmf_cookbook cc
                WHERE cc.classify_pid = $pid  ORDER BY cc.create_time DESC 
                limit  $pages ,8";
        $cookbooksss = $this->cookbook_model->query($sql);
        //查询每个菜谱收藏数
        foreach ($cookbooksss as $vo) {
            $id = $vo['id'];
            $praiseCount = $this->praise_model->where("cook_id = $id")->count();
            $vo['praiseCount'] = $praiseCount;
            $cookbookss[] = $vo;
        }
        //查询每个菜谱留言数
        foreach ($cookbookss as $vo) {
            $id = $vo['id'];
            $reviewCount = $this->review_model->where("cook_id = $id and review_id = 0")->count();
            $vo['reviewCount'] = $reviewCount;
            $cookbooks[] = $vo;
        }
        $this->returnok($cookbooks, 'ok');
    }

    /*
     * 获取一级分类banner及二级分类列表
     */
    public function getClassifyBanner()
    {
        $pid = I('pid');
        $sql1 = "SELECT cb.* ,cc.`name` cookname FROM cmf_banner cb
        LEFT JOIN cmf_cookbook cc ON cc.id = cb.cook_id
        WHERE cb.classify_id = $pid  ORDER BY listorder DESC";
        $banner = $this->banner_model->query($sql1);
        //获取一级分类的二级分类列表
        $sql1 = "SELECT ccs.name,ccs.id,ccs.image  FROM cmf_classify ccs  WHERE ccs.pid = $pid
                ORDER BY ccs.listorder ASC";
        $classifys = $this->classify_model->query($sql1);
        $data['banner'] = $banner; //banner数据
        $data['classify'] = $classifys;//二级分类数据
        $this->returnok($data, 'ok');
    }

    // 根据二级分类id分页获取所有菜谱列表
    public function getSonCookbookList()
    {
        $id = I('id');
        $page = I('page');
        //获取按照推荐查询
        $recommend = I('recommend');
        //获取按照最新查询
        $new = I('isnew');
        $cooking = I('cooking');
        $pages = ($page - 1) * 8;
        $sql = "SELECT * FROM cmf_cookbook cc
                WHERE cc.classify_id = $id   ";
        if ($cooking) {
            $sql .= " AND cc.cooking_id = $cooking";
        }
        if ($recommend == 1) {
            $sql .= " AND cc.recommended = $recommend ORDER BY cc.listorder  limit  $pages ,8 ";
        }
        if ($new == 1) {
            $sql .= " ORDER BY cc.create_time DESC limit  $pages ,8 ";
        }


        $cookbooksss = $this->cookbook_model->query($sql);
        //查询每个菜谱收藏数
        foreach ($cookbooksss as $vo) {
            $id = $vo['id'];
            $praiseCount = $this->praise_model->where("cook_id = $id")->count();
            $vo['praiseCount'] = $praiseCount;
            $cookbookss[] = $vo;
        }
        //查询每个菜谱留言数
        foreach ($cookbookss as $vo) {
            $id = $vo['id'];
            $reviewCount = $this->review_model->where("cook_id = $id and review_id = 0")->count();
            $vo['reviewCount'] = $reviewCount;
            $cookbooks[] = $vo;
        }

        $this->returnok($cookbooks, 'ok');
    }

    //获取烹饪方法列表
    public function getCooking()
    {
        $cooking = $this->cooking_model->select();
        $this->returnok($cooking, 'ok');
    }

    // 根据id获取菜谱详情
    public function getCookbookDetail()
    {
        $cookbookId = I('id');
        $ouId = I('ou_id');
        //用户点击获取菜谱，阅读数+1
        $readNum = $this->cookbook_model->where("id = $cookbookId")->getField('read_num');
        $data = array(
            'read_num' => $readNum + 1
        );
        $this->cookbook_model->where("id = $cookbookId")->save($data);
        $sql = 'SELECT cb.* , cc.name FROM cmf_cookbook cb
LEFT JOIN cmf_classify cc ON cb.classify_pid = cc.id
                WHERE cb.id = ' . $cookbookId;
        $cookbook = $this->cookbook_model->query($sql);

        //获取菜谱点赞数
        $praiseCount = $this->praise_model->where("cook_id = $cookbookId")->count();
        $cookbook[0]['praiseCount'] = $praiseCount;
        //获取当前用户是否已收藏
        $where = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId
        );
        $collectCount = $this->collect_model->where($where)->count();
        $cookbook[0]['collect'] = $collectCount;

        //获取当前用户是否已点赞
        $where = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId
        );
        $count = $this->praise_model->where($where)->count();
        $cookbook[0]['praise'] = $count;
        //获取菜谱最新一条评论
//        $sql = "SELECT cr.*,cou.head_img,cou.`name` username FROM cmf_review cr
//            LEFT JOIN cmf_oauth_user cou ON cou.id = cr.user_id
//            WHERE cr.review_id = 0 AND cr.cook_id = $cookbookId
//                ORDER BY cr.create_time DESC limit 0,1";
//        $reviews = $this->review_model->query($sql);
//        $review = [];

//        $id = $reviews[0]['id'];
//        $sql1 = "SELECT cr.*,cou.head_img,cou.`name` username FROM cmf_review cr
//            LEFT JOIN cmf_oauth_user cou ON cou.id = cr.user_id
//            WHERE cr.review_id = $id AND cr.cook_id = $cookbookId
//                            ORDER BY cr.create_time DESC";
//        $replyss= $this->review_model->query($sql1);
//        $replys = [];
//        foreach($replyss as $co){
//            $replyId = $co['id'];
//            $iamges = $this->review_image_model->where("review_id = $replyId")->select();
//            $co['photos'] = $iamges;
//            $replys[] = $co;
//        }
//        $reviews['replys'] = $replys;
//        $photos = $this->review_image_model->where(array('review_id' => $id))->select();
//        $reviews['photos'] = $photos;

//        $cookbook[0]['review'] = $reviews;

        $this->returnok($cookbook, 'ok');
    }

    //获取菜谱详情页评论
    public function getReview()
    {
        $cookbookId = I('id');
        $sql = 'SELECT * FROM cmf_cookbook cb
                WHERE cb.id = ' . $cookbookId;
        $cookbook = $this->cookbook_model->query($sql);
        //获取菜谱最新一条评论
        $sql = "SELECT cr.*,cou.`avatar` head_img,cou.`user_nicename` username FROM cmf_review cr  
            LEFT JOIN cmf_users cou ON cou.id = cr.uid
            WHERE cr.review_id = 0 AND cr.cook_id = $cookbookId 
                ORDER BY cr.create_time DESC limit 0,1";
        $reviews = $this->review_model->query($sql);

        $id = $reviews[0]['id'];
        if ($id > 0) {
            $sql1 = "SELECT cr.*,cou.`avatar` head_img,cou.`user_nicename` username FROM cmf_review cr  
            LEFT JOIN cmf_users cou ON cou.id = cr.uid
            WHERE cr.review_id = $id AND cr.cook_id = $cookbookId
                            ORDER BY cr.create_time DESC";
            $replyss = $this->review_model->query($sql1);
            $replys = [];
            foreach ($replyss as $co) {
                $replyId = $co['id'];
                $iamges = $this->review_image_model->where("review_id = $replyId")->select();
                $co['photos'] = $iamges;
                $replys[] = $co;
            }
            $reviews['replys'] = $replys;
            $photos = $this->review_image_model->where(array('review_id' => $id))->select();
            $reviews['photos'] = $photos;

//        $cookbook[0]['review'] = $reviews;
        }


        $this->returnok($reviews, 'ok');
    }

    //用户收藏添加记录
    public function addCollect()
    {
        $cookbookId = I('id');
        $ouId = I('ou_id');
        $data = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId,
            'create_time' => date("Y-m-d H:i:s", time())
        );
        $collectId = $this->collect_model->add($data);
        $this->returnok('', 'ok');
    }

    //用户取消收藏
    public function cancleCollect()
    {
        $cookbookId = I('id');
        $ouId = I('ou_id');
        $data = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId
        );
        $this->collect_model->where($data)->delete();
        $this->returnok('', 'ok');
    }

//用户点赞添加记录
    public function addPraise()
    {
        $cookbookId = I('id');
        $ouId = I('ou_id');
//        $this->returnok($cookbookId, 'ok');
        $data = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId,
            'create_time' => date("Y-m-d H:i:s", time())
        );
        $praiseId = $this->praise_model->add($data);
        $this->returnok('', 'ok');
    }

    //用户取消收藏
    public function canclePraise()
    {
        $cookbookId = I('id');
        $ouId = I('ou_id');
        $data = array(
            'cook_id' => $cookbookId,
            'ou_id' => $ouId
        );
        $this->praise_model->where($data)->delete();
        $this->returnok('', 'ok');
    }


    // 获取用户收藏的所有菜谱列表
    public function getCollectCookbookList()
    {
        $ouId = I('ou_id');
        $page = I('page');
        $pages = ($page - 1) * 8;
        $sql = "SELECT cb.* FROM cmf_cookbook cb
                LEFT JOIN  cmf_collect cc ON cb.id = cc.cook_id
                WHERE cc.ou_id = $ouId  ORDER BY cc.create_time DESC 
                limit  $pages ,8";
        $cookbooksss = $this->cookbook_model->query($sql);
        //查询每个菜谱收藏数
        foreach ($cookbooksss as $vo) {
            $id = $vo['id'];
            $praiseCount = $this->praise_model->where("cook_id = $id")->count();
            $vo['praiseCount'] = $praiseCount;
            $cookbookss[] = $vo;
        }
        //查询每个菜谱留言数
        foreach ($cookbookss as $vo) {
            $id = $vo['id'];
            $reviewCount = $this->review_model->where("cook_id = $id and review_id = 0")->count();
            $vo['reviewCount'] = $reviewCount;
            $cookbooks[] = $vo;
        }
        $this->returnok($cookbooks, 'ok');
    }

    /**
     * 上传图片
     */
    public function uploadPhoto()
    {
        $upload_setting = sp_get_upload_setting();

        $filetypes = array(
            'image' => array('title' => 'Image files', 'extensions' => $upload_setting['image']['extensions']),
            'video' => array('title' => 'Video files', 'extensions' => $upload_setting['video']['extensions']),
            'audio' => array('title' => 'Audio files', 'extensions' => $upload_setting['audio']['extensions']),
            'file' => array('title' => 'Custom files', 'extensions' => $upload_setting['file']['extensions'])
        );

        if (IS_POST) {
            $all_allowed_exts = array();
            foreach ($filetypes as $mfiletype) {
                array_push($all_allowed_exts, $mfiletype['extensions']);
            }
            $all_allowed_exts = implode(',', $all_allowed_exts);
            $all_allowed_exts = explode(',', $all_allowed_exts);
            $all_allowed_exts = array_unique($all_allowed_exts);

            $file_extension = sp_get_file_extension($_FILES['file']['name']);
            $upload_max_filesize = $upload_setting['upload_max_filesize'][$file_extension];
            $upload_max_filesize = empty($upload_max_filesize) ? 2097152 : $upload_max_filesize;//默认2M

            $app = I('app', '');
            if (!in_array($app, C('MODULE_ALLOW_LIST'))) {
                $app = 'default';
            } else {
                $app = strtolower($app);
            }

            $savepath = $app . '/' . date('Ymd') . '/';
            //上传处理类
            $config = array(
                'rootPath' => './' . C("UPLOADPATH"),
                'savePath' => $savepath,
                'maxSize' => $upload_max_filesize,
                'saveName' => array('uniqid', ''),
                'exts' => $all_allowed_exts,
                'autoSub' => false,
            );
            $upload = new \Think\Upload($config);//
            $info = $upload->upload();
            //开始上传
            if ($info) {
                $info1 = '
                {"myPhoto":{
                "name":"tmp_1739677770o6zAJs0gvGLIX1B80zY9OKe76IdI9255c54eedb64ede9dd19a571b6731a0 . jpg",
                "type":"image\/jpeg",
                "size":142205,
                "key":"myPhoto",
                "ext":"jpg",
                "md5":"85b101287cc295975b3fdbbf9b3f9a7f",
                "sha1":"c6ab00864e74ae48f6c4c5ab4fd205a1f69f354d",
                "savename":"592e7cafbf8f4 . jpg",
                "savepath":"data\/upload\/meal\/20170531\/"}}';

                //上传成功
                exit(json_encode($info));
            } else {
                $this->ajaxReturn(array('name' => '', 'status' => 0, 'message' => $upload->getError()));
            }
        }
    }

}
